package com.slipper.ai.model.chat.support;

import com.slipper.ai.model.chat.ChatModelBuilder;
import com.slipper.constants.Constants;
import com.slipper.core.gson.GsonUtil;
import com.slipper.exception.CommonException;
import com.slipper.system.ai.bo.AiModelBO;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.ollama.OllamaChatModel;
import org.springframework.ai.ollama.api.OllamaApi;
import org.springframework.ai.ollama.api.OllamaOptions;

import java.util.Map;

public class OllamaChatModelBuilder implements ChatModelBuilder {
    @Override
    public ChatModel build(AiModelBO model) {
        Map<String, Object> options = GsonUtil.toMap(model.getParamJson());
        if (options == null || options.isEmpty() || !options.containsKey("apiUrl")) {
            throw new CommonException("参数配置不正确！");
        }

        OllamaOptions.Builder builder = OllamaOptions.builder().model(model.getSupplierModelName());
        if (Constants.YES.equals(options.get("use_temperature")) && options.get("temperature") != null) {
            builder.temperature((double) options.get("temperature"));
        }
        if (Constants.YES.equals(options.get("use_top_p")) && options.get("top_p") != null) {
            builder.topP((double) options.get("top_p"));
        }
        if (Constants.YES.equals(options.get("use_presence_penalty")) && options.get("presence_penalty") != null) {
            builder.presencePenalty((double) options.get("presence_penalty"));
        }
        if (Constants.YES.equals(options.get("use_frequency_penalty")) && options.get("frequency_penalty") != null) {
            builder.frequencyPenalty((double) options.get("frequency_penalty"));
        }
        if (Constants.YES.equals(options.get("use_max_tokens")) && options.get("max_tokens") != null) {
            builder.numPredict((int) options.get("max_tokens"));
        }

        String apiUrl = (String) options.get("apiUrl");
        return OllamaChatModel.builder()
                .ollamaApi(OllamaApi
                        .builder()
                        .baseUrl(apiUrl)
                        .build())
                .defaultOptions(builder.build())
                .build();
    }
}
